//******************************************************************
//******************************************************************
//**********          ANts Peer To Peer Sources        *************
//
// ANts P2P realizes a third generation P2P net. It protects your
// privacy while you are connected and makes you not trackable, hiding
// your identity (ip) and crypting everything you are sending/receiving
// from others.

// Copyright (C) 2004  Roberto Rossi

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

package ants.p2p.utils.net;

import ants.p2p.NeighbourAnt;
import java.io.*;
import java.net.SocketException;
import java.net.SocketTimeoutException;

public class BandwidthFilterIn extends java.io.FilterInputStream {

	// BandwidthFilterControlerIn controler;
	static int used = 0;

	// int limit;

	// Constructors
	public BandwidthFilterIn(InputStream o) {
		super(o);
		// limit = 1024*10;
		// controler = new BandwidthFilterControlerIn(this, 1000);
		// controler.start();
	}

	/*
	 * public BandwidthFilterIn(InputStream o, int bandwidth){ super(o); //limit =
	 * bandwidth; controler = new BandwidthFilterControlerIn(this, 1000);
	 * controler.start(); } public BandwidthFilterIn(InputStream o, int
	 * bandwidth, int timeSlotLength){ super(o); //limit = bandwidth; controler =
	 * new BandwidthFilterControlerIn(this, timeSlotLength); controler.start(); }
	 * 
	 * public void setLimit(int limit){ this.limit = limit; this.used = 0; }
	 */

	/*
	 * protected synchronized void doNotify(){ notify(); }
	 */

	protected void bandwidthCheck() {
		synchronized (BandwidthFilterControlerIn.getInstance()) {
			if (used >= NeighbourAnt.bandwidthLimit) {
				try {
					// System.out.println("Bandwidth Limit Reached..");
					BandwidthFilterControlerIn.getInstance().wait();
				} catch (Exception e) {
				}
			}
		}
	}

	// Standerd Interfaces
	public int read() throws IOException {
		this.bandwidthCheck();
		/*
		 * Attempt to read, catching the exception if it fails. If the
		 * connection times out, though, the connection is still open, it just
		 * doesn't have anything to read.
		 */
		int num = 0;
		num = in.read();
		used++;
		return num;
	}

	public int read(byte dest[]) throws IOException {
		int toBeRead = dest.length;
		int available = in.available();
		int numRead = 0;
		int totRead = 0;
		// while(toBeRead > 0 && numRead >= 0){
		this.bandwidthCheck();
		if (available <= (NeighbourAnt.bandwidthLimit - used)
				&& available <= toBeRead) {
			int val = Math.min((NeighbourAnt.bandwidthLimit - used), toBeRead);
			byte[] readBytes = new byte[val];
			numRead = in.read(readBytes);
			if (numRead >= 0) {
				System.arraycopy(readBytes, 0, dest, dest.length - toBeRead,
						numRead);
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		} else if (available <= (NeighbourAnt.bandwidthLimit - used)
				&& available > toBeRead) {
			byte[] readBytes = new byte[toBeRead];
			numRead = in.read(readBytes);
			if (numRead >= 0) {
				System.arraycopy(readBytes, 0, dest, dest.length - toBeRead,
						numRead);
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		} else if (available > (NeighbourAnt.bandwidthLimit - used)) {
			int val = Math.min((NeighbourAnt.bandwidthLimit - used), toBeRead);
			byte[] readBytes = new byte[val];
			numRead = in.read(readBytes);
			if (numRead >= 0) {
				System.arraycopy(readBytes, 0, dest, dest.length - toBeRead,
						numRead);
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		}
		// }
		return totRead == 0 ? numRead : totRead;
	}

	public int read(byte dest[], int off, int len) throws IOException {
		byte[] newByteArray = new byte[len];
		int result = 0;
		result = this.read(newByteArray);
		if (result >= 0)
			System.arraycopy(newByteArray, 0, dest, off, result);
		return result;
	}

	public long skip(long numBytes) throws IOException {
		long toBeRead = numBytes;
		long available = in.available();
		long numRead = 0;
		long totRead = 0;
		// while(toBeRead > 0 && numRead >= 0){
		this.bandwidthCheck();
		if (available <= (NeighbourAnt.bandwidthLimit - used)
				&& available <= toBeRead) {
			long val = Math.min((NeighbourAnt.bandwidthLimit - used), toBeRead);
			numRead = in.skip(val);
			if (numRead >= 0) {
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		} else if (available <= (NeighbourAnt.bandwidthLimit - used)
				&& available > toBeRead) {
			numRead = in.skip(toBeRead);
			if (numRead >= 0) {
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		} else if (available > (NeighbourAnt.bandwidthLimit - used)) {
			long val = Math.min((NeighbourAnt.bandwidthLimit - used), toBeRead);
			numRead = in.skip(val);
			if (numRead >= 0) {
				toBeRead -= numRead;
				totRead += numRead;
				used += numRead;
			}
		}
		// }
		return totRead == 0 ? numRead : totRead;
	}

	public void close() throws IOException {
		// if (controler.isAlive()) controler.stop();
		in.close();
	}

	public void finalize() throws Throwable {
		// if (controler.isAlive()) controler.stop();
	}
}
